<template>
  <div>
    <el-table
      :data="tableData"
      border
      v-loading="loading"
      ref="tableRef"
      @sort-change="remoteSort"
    >
      <slot></slot>
    </el-table>
    <div class="flex mt-$layout-padding justify-end">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 30, 50, 100]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { getTableData } from "@/api/common";
import type { AnyObject } from "@/types";
import type { TableInstance } from "element-plus";
import { ref, watch } from "vue";

const props = withDefaults(
  defineProps<{
    url: string; // 接口地址
    query?: AnyObject; // 查询参数
  }>(),
  {
    query: () => ({})
  }
);

const tableRef = ref<TableInstance>();

// 排序相关
const remoteSort = (ctx: { column: any; prop: any; order: any }) => {
  console.log(ctx);
};

// 获取表格数据
const loading = ref(false);
const tableData = ref<any[]>([]); // 表格数据
const total = ref(0); // 总数
const getData = () => {
  loading.value = true;

  const queryOption = {
    size: pageSize.value,
    current: currentPage.value,
    context:null,
    ...props.query
  }

  if(props.query.hasOwnProperty('timeRange')) {
    if(Array.isArray(props.query.timeRange) && props.query.timeRange.length === 2) {
      queryOption['beginTime'] = props.query.timeRange[0];
      queryOption['endTime'] = props.query.timeRange[1];
    }
    delete queryOption['timeRange'];
  }

  getTableData(props.url, queryOption)
    .then((data) => {
      tableData.value = data.records;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
// query改变重新获取数据
// watch(() => props.query, () => {
  
//   getData();
// }, {
//   deep: true
// });

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const small = ref(false);
const disabled = ref(false);
const background = ref(true);
const handleSizeChange = (val: number) => {
  getData();
};
const handleCurrentChange = (val: number) => {
  getData();
};

getData();

// 暴露接口
defineExpose({
  getSelectionRows() {
    return tableRef.value?.getSelectionRows();
  },
  reload() {
    getData();
  },
  reset() {
    pageSize.value = 10;
    currentPage.value = 1;
    getData();
  },
  clearSort() {
    tableRef.value?.clearSort();
  }
});
</script>
<style lang="scss" scoped>


table {
  table-layout: auto !important;
}
.el-table__header {
  width: 100% !important;
}
.el-table__body {
  width: 100% !important;
}


 
</style>

